package com.huang.community.controller;

import com.huang.community.common.CommunityConstant;
import com.huang.community.model.NewPage;
import com.huang.community.service.Imp.DiscussPostServiceImpl;
import com.huang.community.service.LikeService;
import com.huang.community.service.UserService;
import com.huang.community.pojo.DiscussPost;
import com.huang.community.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 首页控制器
 * @author TianTian
 * @date 2022/4/28 21:39
 */
@Controller
public class indexController implements CommunityConstant {
    @Autowired
    DiscussPostServiceImpl discussPostServiceImp;
    @Autowired
    UserService userService;
    @Autowired
    private LikeService likeService;
    //首页
    @GetMapping("/index")
    public String getIndexPage(Model model, NewPage newPage,
                               @RequestParam(name = "orderMode", defaultValue = "0") int orderMode) {
        System.out.println(newPage);
        // 方法调用钱,SpringMVC会自动实例化Model和NewPage,并将NewPage注入Model.
        // 所以,在thymeleaf中可以直接访问NewPage对象中的数据.
        HashMap<String, Object> hm = discussPostServiceImp.findDiscussPosts(null, newPage.getCurrent(), newPage.getLimit(),orderMode);
        newPage.setRows((int)hm.get("total"));
        newPage.setPath("/index");

        List<DiscussPost> list = (List<DiscussPost>) hm.get("discussPosts");
        List<Map<String, Object>> discussPosts = new ArrayList<>();
        if (list != null) {
            for (DiscussPost post : list) {
                Map<String, Object> map = new HashMap<>();
                //传入帖子
                map.put("post", post);
                User user = userService.findUserById(post.getUserId());
                //传入用户信息
                map.put("user", user);

                //新增加的方法 点赞数量
                long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, post.getId());
                map.put("likeCount", likeCount);

                discussPosts.add(map);
            }
        }
        model.addAttribute("discussPosts", discussPosts);
        model.addAttribute("orderMode",orderMode);
        return "/index";
    }
    @GetMapping("/erorr")
    public String getError(){
        return "/error/500";
    }
}
